package com.gyf.bos.dao.base;

import com.gyf.bos.dao.base.IBaseDao;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class BaseDaoImpl<T> implements IBaseDao<T> {

    private Class<T> entityClass;//泛型类
    @Autowired
    protected HibernateTemplate hibernateTemplate;

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    public BaseDaoImpl() {

        System.out.println(this.getClass().toString());
        //1.获得父类【BaseDaoImpl<T>】的参数化类型
        ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
        System.out.println(genericSuperclass.toString());
        //2.获得父类的参数化类型的数组
        Type[] types = genericSuperclass.getActualTypeArguments();
        System.out.println(types[0].toString());
        //3.获取泛型类第一个参数化的类型
        entityClass = (Class<T>) types[0];
        System.out.println(entityClass.toString());
    }

    @Override
    public void save(T entity) {
        hibernateTemplate.save(entity);
    }

    @Override
    public void update(T entity) {
        hibernateTemplate.update(entity);
    }

    @Override
    public void delete(T entity) {
        hibernateTemplate.delete(entity);
    }

    @Override
    public List findAll() {
        //entityClass.getSimpleName() 获取类名
        String hql = "from " + entityClass.getSimpleName();
        System.out.println("hql:" + hql);
        return this.hibernateTemplate.find(hql);
    }

    @Override
    public T findById(Serializable id) {

        return this.hibernateTemplate.get(entityClass,id);
    }

    @Override
    public void executeUpdate(String hql, Object... objs) {

        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery(hql);
        for (int i = 0; i <objs.length ; i++) {
            query.setParameter(i, objs[i]);
        }
        query.executeUpdate();
    }
}
